import os
import argparse
import subprocess
import time
import re

# hosts 文件的路径
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"

def update_hosts(ip, host):
    try:
        # 读取当前的 hosts 文件内容
        with open(hosts_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        # 移除现有的指定域名相关条目
        new_lines = []
        for line in lines:
            if host not in line:
                new_lines.append(line)

        # 添加新的指定 IP 和域名映射条目
        new_entry = f"{ip} {host}\n"
        new_lines.append(new_entry)

        # 将更新后的内容写回 hosts 文件
        with open(hosts_path, 'w', encoding='utf-8') as file:
            file.writelines(new_lines)

        print("hosts 文件更新成功！")
    except Exception as e:
        print(f"更新 hosts 文件时出错: {e}")

def get_github_ip(domain):
    try:
        result = subprocess.run(['nslookup', domain], capture_output=True, text=True)
        output = result.stdout
        ip_pattern = r'Address: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
        match = re.search(ip_pattern, output)
        if match:
            return match.group(1)
        else:
            print(f"未找到 {domain} 的 IP 地址。")
            return None
    except Exception as e:
        print(f"执行 nslookup 时出错: {e}")
        return None

def main():
    github_domains = ["github.com", "github.global.ssl.fastly.net"]
    while True:
        for domain in github_domains:
            ip = get_github_ip(domain)
            if ip:
                update_hosts(ip, domain)
        print("本次更新完成，等待下一次更新...")
        time.sleep(3600)  # 每隔 1 小时（3600 秒）执行一次

if __name__ == "__main__":
    main()
    